<template>
	<view class="install-container" style="margin-bottom: 30rpx;">
	
		<!-- 用户信息 -->
		<!-- 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，
		这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则 -->
		<uni-forms :value="params" ref="form" validateTrigger="bind" class="word5">
			<uni-forms-item required label="申请人：" name="申请人">
				<input maxlength="50" placeholder="请输入起始楼层号" v-model="params['申请人']" @input="binddata('申请人',$event.detail.value)">
			</uni-forms-item>
			<!-- <uni-forms-item required label="申请单位：" name="所属单位">
				<input disabled type="number" maxlength="18" v-model="params['所属单位']" placeholder="请输入楼层数量" @input="binddata('所属单位',$event.detail.value)" >
			</uni-forms-item> -->
			<uni-forms-item required label="采购人员：" name="采购人员">
				<!-- <input maxlength="50" placeholder="请输入起始楼层号" v-model="params['起始楼层号']" @input="binddata('起始楼层号',$event.detail.value)"> -->
				<song-data-picker :localdata="personList" popup-title="请选择采购人员" :openSearch="true" @change="onchange"
					@nodeclick="onnodeclick"></song-data-picker>
			</uni-forms-item>
			<uni-forms-item v-show="totalPrice" required label="采购总金额：" name="采购总金额">
				<input disabled type="number" maxlength="18" v-model="totalPrice">
			</uni-forms-item>
			<uni-forms-item required label="采购原因：" name="采购备注">
				<input type="text" maxlength="18" v-model="params['采购备注']" placeholder="请输入采购原因" @input="binddata('采购备注',$event.detail.value)" >
			</uni-forms-item>
			<!-- <uni-forms-item required label="所属楼栋：" name="楼栋id">
				<view :class="label == '请选择所属楼栋' ? 'color':''" class="tap" @click="handleTap('picker')">{{label}}</view>
				<lb-picker ref="picker" @click="handleTap('picker')" v-model="params['楼栋id']"
				 mode="selector" :list="buildList" :dataset="{ name: 'label' }" @confirm="handleConfirm" @cancel="handleCancel">
				</lb-picker>
			</uni-forms-item> -->
			<button class="material-form-btn" @click="submitForm">提交</button>
		</uni-forms>
		<view style="height: 30rpx;"></view>
		<uploader v-model="params['图片']"></uploader>
		<view class="line"></view>
		<view v-if="params['材料清单'].length">
			<view class="detail-title">
				<text>采购明细</text>
			</view>
			<purchaseItem @total="getTotalPrice" @changeClass="changeClass" @changeName="changeName" @changeNum="handleChangeNum" @change="onPrice" :storeId="params['仓库id']" @delete="handleDelete" :classList="classList" :ref="'material'+item.id" :params.sync="item" :key="item.id" v-for="item in params['材料清单']"></purchaseItem>			
		</view>
		<view @click="onAdd" class="choose-box">
			<text style="font-size: 50rpx;margin-right: 10rpx;">+</text>
			<text>添加</text>
		</view>
		<!-- <view class="title">
			<view class="left">采购列表</view>
			<view class="right">
				<text class="add" @click="goAdd">
					+
				</text>
				<text @click="goAdd" style="color: #1152FC;">添加</text>
			</view>
		</view>
		<view class="choose-container">
			<purchase-item @delete="handleDelete" @change="handleChange" :purchaseList="params['材料清单']"  v-if="params['材料清单'].length"></purchase-item>
			<view v-else>
				<van-empty description="暂无耗材"></van-empty>
			</view>
		</view> -->
	</view>
</template>

<script>
	import uploader from '@/components/my-components/image-uploader.vue'
	import LbPicker from '@/components/lb-picker/index.vue'
	import PurchaseItem from './purchaseItem.vue'
	import dayjs from 'dayjs'
	export default {
		components: {
			uploader,
			LbPicker,
			PurchaseItem
		},
		data() {
			return {
				totalPrice: 0,
				classList: [],
				personList: [],
				label: '请选择所属楼栋',
				label1: '请选择所属单元',
				params: {
					申请人id: null,	
					申请人: null,
					所属机构id: this.$config.groupId,
					所属机构: uni.getStorageSync('groupName'),
					所属单位id: null,
					所属单位: null,
					采购人员id: null,
					采购人员: null,
					采购备注: null,	
					图片	: [],		
					材料清单: []
				},
				params1: {
					检查点id: null,
					网格id: null,
					楼栋id: null
				},
				params2: {
					类型分类: 2,
					pagination: {
						current: 1,
						pageSize: 1000
					},
					sorter: {
						field: "id",
						order: 0
					}
				},
				//表单验证规则
				rules: {
					申请人: {
						rules: [{
							required: true,
							errorMessage: '请填写所属楼栋',
						}]
					},
					采购人员: {
						rules: [{
							required: true,
							errorMessage: '请选择采购人员',
						}]
					},
					采购备注: {
						rules: [{
							required: true,
							errorMessage: '请填写采购原因',
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		computed: {
			// totalPrice() {
			// 	let list = uni.getStorageSync('purchaseList') || []
			// 	let sum = 0
			// 	for(let i = 0; i < list.length; i++) {
			// 			sum += list[i].总价
			// 	}
			// 	return sum
			// }
		},
		onLoad(options) {
			this.params.申请人 = uni.getStorageSync('userInfo').name
			this.params.所属单位 =  uni.getStorageSync('label')
			this.params.申请人id = uni.getStorageSync('userInfo').id
			this.params.所属单位id = uni.getStorageSync('currentUnitId')
			this.params.所属机构 = uni.getStorageSync('groupName')
			this.getPersonList(this.params.所属单位id)
			this.getClassList()
		},
		onShow() {
			
		},
		onUnload() {
			uni.removeStorageSync('purchaseList')
		},
		methods: {
			getTotalPrice(list) {
				let sum = 0
				list.forEach(item => {
					sum += item.总价
				})
				this.totalPrice = sum
			},
			changeClass({id, value}) {
				const index = this.params.材料清单.findIndex(item => item.id === id)
				this.params.材料清单[index].类型名称 = value
			},
			changeName({id, value}) {
				const index = this.params.材料清单.findIndex(item => item.id === id)
				this.params.材料清单[index].物料id = value 
			},
			handleChangeNum({id, num}) {
				const index = this.params.材料清单.findIndex(item => item.id === id)
				this.params.材料清单[index].数量 = num 
			},
			onPrice({id, price}) {
				const index = this.params.材料清单.findIndex(item => item.id === id)
				this.params.材料清单[index].总价 = price
			},
			handleDelete(e) {
				// console.log(e)
				let purchaseList = uni.getStorageSync('purchaseList') || []
				const index = this.params.材料清单.findIndex(item => item.id === e)
				const aIndex = purchaseList.findIndex(item => item.id === e)
				if(aIndex > -1) {
					purchaseList.splice(aIndex, 1)
					uni.setStorageSync('purchaseList', purchaseList)
				}
				this.params.材料清单.splice(index, 1)
			},
			async getClassList() {
				uni.showLoading({
					mask: true
				})
				const res = await this.$http.post('/property/typeSetting/list', this.params2)
				if(res.code === 10000) {
					// console.log(res)
					res.data.list = res.data.list || []
					res.data.list.forEach(item => {
						item.text = item.类型名称
						item.value = item.类型id
					})
					this.classList = res.data.list
				}
			},
			onAdd() {
				this.params.材料清单.push({
					id: Date.now(),
					类型名称: null,
					物料名称: null,
					物料id: null,
					数量	: 1,
					总价: null,
					计量单位: null,
					规格型号: null
				})
				// console.log(this.params.材料清单)
			},
			
			onchange(e) {
			  const value = e.detail.value
			  this.params.采购人员 = value[0].人员名称
			  this.params.采购人员id = value[0].id
			  this.binddata('采购人员', this.params.采购人员)
			},
			getPersonList(id) {
				this.$http.post('worksys/worker/list', {单位id: id, 状态: 1}).then(res => {
					console.log(res, '处理人员')
					if (res.code === 10000) {
						res.data.list = res.data.list || []
						res.data.list.forEach(item => {
							item.value = item.id
							item.text = item.人员名称
						})
						this.personList = res.data.list
					}
				})
			},
			handleTap(name) {
				this.$refs[name].show()
			},
			handleConfirm(e) {
				// console.log(this.params.户主关系)
				if (e) {
					const name = e.dataset.name
					const label = e.item.label
					this.params.楼栋id = e.item.楼栋id
					if (name && label) {
						this[name] = label
					}
				}
			},
			submitForm(form) {
				// console.log('this.resident', this.params.材料清单)
				let isValidate = true
				for(let i = 0; i < this.params.材料清单.length; i++) {
					if(!this.$refs['material' + this.params.材料清单[i].id][0].validate()) {
						isValidate = false
					}
				}
				if(isValidate) {
					this.$refs.form.submit().then(res => {
						console.log('通过')
						let purchaseList = uni.getStorageSync('purchaseList') || []
						if(!purchaseList.length) {
							uni.showToast({
								title: '请添加采购列表',
								icon: 'none'
							})
							return
						}
						const flag = purchaseList.some(item => item.单价 < 0)
						if(flag) {
							uni.showToast({
								title: '采购单价不能为负数',
								icon: 'none'
							})
							return
						}
						let obj = Object.assign({}, this.params, {材料清单: purchaseList})
						// console.log('obj', obj)
						this.addPurchase(obj)
					}).catch(err => {
						console.log('表单错误信息：', err);
						uni.showToast({
							icon: 'none',
							title: "表单字段填写错误，请检查"
						})
					})
				}
			},
			addPurchase(params) {
				uni.showLoading()
				this.$http.post('/property/purchase/create',params).then(res => {
					if(res.code === 10000) {
						console.log(res)
						uni.redirectTo({
							url: '/ticketSystem/acceptSuccess/acceptSuccess?path=/pages/service/service' + '&title=返回服务页面'
						})
						// uni.redirectTo({
						// 	url: '/ticketSystem/acceptSuccess/acceptSuccess?path=/materialSystem/index/index' + '&title=返回物料首页'
						// })
						uni.removeStorageSync('purchaseList')
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.detail-title {
		padding-left: 40rpx;
		padding-top: 20rpx;
		position: relative;
		font-size: 32rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		&:before {
			position: absolute;
			content: '';
			width: 6rpx;
			height: 36rpx;
			left: 20rpx;
			top: 24rpx;
			background-color: #1064E9;;
		}
	}
	.choose-box {
		font-size: 40rpx;
		color: #1152FC;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
	}
	.title {
		position: relative;
		padding: 0 20rpx 0 40rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 40rpx;
		font-size: 34rpx;
		.left {
			font-size: 32rpx;
			&:before {
				content: '';
				position: absolute;
				top: 10rpx;
				left: 24rpx;
				width: 6rpx;
				height: 34rpx;
				background-color: #1152FC;
			}
		}
		.right {
			// display: flex;
		}
		.add {
			font-size: 32rpx;
			font-weight: bold;
			color: #1152FC;
			margin-right: 10rpx;
		}
	}
	.line {
		margin: 40rpx 20rpx;
		width: 710rpx;
		height: 2rpx;
		background-color: #ccc;
	}
	.install-container {
		padding-bottom: 90rpx;
		// height: 100vh;
		// background-color: #F8F8F8;
	}
	.color {
		color: #808080;
	}
	.tap {
		display: flex;
		align-items: center;
	}
</style>

